<template>
	
	<!-- 
		该页面其实有四种显示化状态：搜索前、搜索中、搜索后-成功、搜索后-失败
	-->
<div>
	<h3 v-if="firstView">亲，请输入用户搜索您喜欢的内容哦~~~</h3>
	<h3 v-if="loading">loading...</h3>
	<h3 v-if="errorMsg">{{errorMsg}}</h3>
	<div class="row">
		<div class="card" v-for="(user, index) in users" v-bind:key="index">
			<a v-bind:href="user.url" target="_blank">
				<img v-bind:src="user.avatar_url" style='width: 100px'/>
			</a>
			<p class="card-text">{{user.name}}</p>
		</div>
	</div>
</div>
</template>

<script>
	import PubSub from 'pubsub-js' // 引入消息订阅类库, 兄弟组件间通信用这个非常舒服
	import axios from 'axios' // 引入axios
	export default {
		data() {
			return {
				firstView:true,
				loading:false,
				users:null,
				errorMsg:''
			}
		},
		mounted(){
			// 订阅 Search发布的消息
			PubSub.subscribe('search', (msg, searchName) => { // 需要发送ajax请求，去进行搜索
				const url = 'https://api.github.com/search/users?q=' + searchName;
				
				// 更新状态
				this.firstView = false;
				this.loading = true;
				this.users = null; // 用户每次点击搜索，清空数据
				this.errorMsg = '';
				
				// 发送请求
				axios.get(url).then(response => {
					const result = response.data;
					
					// 接口中数据的名称和我在这里定义的名称不一致，这个时候需要使用map 一一对应
					const users = result.items.map(item => ({
						url:item.html_url,
						avatar_url:item.avatar_url,
						name:item.login
					}));
					
					if(users.length === 0) {
						this.loading = true;
					}
					
					// 成功获取数据，更新页面状态
					this.loading = false;
					this.users = users;
				}).catch(error => {
					// 获取接口数据失败
					this.loading = false;
					this.errorMsg = '看你还嘚瑟，请求失败了吧';
				});
			});
		}
	}
</script>

<style>
.card {
  float: left;
  width: 33.333%;
  padding: .75rem;
  margin-bottom: 2rem;
  border: 1px solid #efefef;
  text-align: center;
}

.card > img {
  margin-bottom: .75rem;
  border-radius: 100px;
}

.card-text {
  font-size: 85%;
}
</style>
